let fs = require('fs')
const compose = require('koa-compose')
module.exports = function hotLoadRouter(path,app) {  
  path = require.resolve(path,{paths : [process.cwd()] })
  //remove route function from middleware
  if(!app.unuse) app.unuse = (fn)=>~app.middleware.indexOf(fn) && app.middleware.splice(app.middleware.indexOf(fn),1)
  let rerr = null
  //require a koa-router().routers
  let routers = require(path)
  //routers could be an Array of koa-mount(path,handler())
  if(routers instanceof Array) routers = compose(routers)
  app.use(routers)
  
  let watcher = fs.watch(path,(etype)=>{
    //remove routers module from require cache
    delete require.cache[require.resolve(path)]
    try{
      app.unuse(routers)
      hotLoadRouter(path,app)
      watcher.close()
    }catch(e){
      //when module file delete or rename
      console.log(e)
      rerr = e
    }
  })
}